/**
 * Created by Administrator on 2019/1/14/014.
 */
//document.oncontextmenu=new Function("event.returnValue=false");
(function($){  
    //备份jquery的ajax方法  
    var _ajax=$.ajax;  
      
    //重写jquery的ajax方法  
    $.ajax=function(opt){  
        //扩展增强处理  
        var _opt = $.extend(opt,{  
            error:function(XMLHttpRequest, textStatus, errorThrown){  
            	if(XMLHttpRequest.status == '999'){
            		top.layer.alert("操作失败：session过期，请重新登录！", {icon: 2, title: '提示'});
            	}else{
            		top.layer.alert("操作失败：请求异常", {icon: 2, title: '提示'});
            	}
            },  
        });  
        _ajax(_opt);  
    };  
})(jQuery);

var showLoading = function(){
    $(".window_loading").show();
}
var hideLoading = function(){
    $(".window_loading").hide();
}

//清空字典选择
var clearInput = function (inputId){
    $("#"+inputId).val("");
}
//获取树形菜单json数据
function getTreeData(zddm,sjdm) {
    var reqData={"zddm":zddm,"sjdm":sjdm};
    $.ajax({
        type:"POST",
        async:false,
        dataType:"json",
        url: ctx+"/dict/listTree" ,
        data:reqData,
        success : function(data) {
            retData = data;
        },
        error : function() {
            alert("请求异常");
        }
    })
    return retData;
}
//获取字典数据
function getCodeData(zddm,filterSql) {
    var reqData={"zddm":zddm,"filterSql":filterSql};
    $.ajax({
        type:"POST",
        async:false,
        dataType:"json",
        url: ctx+"/dict/listCode/"+zddm ,
        data:reqData,
        success : function(data) {
            retData = data;
        },
        error : function() {
            alert("请求异常");
        }
    })
    return retData;
}
$(function () {
    dicInit();
})

var dicInit = function (){
    //绑定点击事件(点击获取json字典数据、展示tree div）
    $('input[data-jzd-type]').off('click').on("click",function (e) {
        e.stopPropagation();
        //获取type值（zddm)、存放dm元素id、存放mc元素id
        var lt = $(this).offset().left;
        var tp =  $(this).offset().top;
        $("#treeDiv").css({
            left: lt + 5,
            top: tp + $(this).parent().height() + 3
        });
        $("#treeDiv").stop().slideDown(300);

        // data-jzd-type="code" 字典类型，code为单级字典，无需树形菜单，访问/dict/listCode/{zddm}；tree为树形菜单，访问/dict/listTree；
        // data-jzd-code="508" 字典项，对应字典代码（zddm) 若为dept 则查询单位表
        // data-jzd-filter=""  过滤SQL
        // data-jzd-dm="jgdm"  选中字典中dm回填的元素ID
        // data-jzd-mc="jgmc" 选中字典中mc回填的元素ID
        var zddm = $(this).attr("data-jzd-code");
        var dmId = $(this).attr("data-jzd-dm");
        var mcId = $(this).attr("data-jzd-mc");
        var filterSql = $(this).attr("data-jzd-filter");
        var zdType = $(this).attr("data-jzd-type");

        var data;
        if(zdType=='code'){
            data = getCodeData(zddm,filterSql);
        }else if(zdType=='tree'){
            data = getTreeData(zddm,null);
        }
        $('#tree').treeview({data:data,levels:1,showTags:true,loadingIcon:"fa fa-hourglass"});
        //选中节点事件
        $('#tree').on('nodeSelected', function(event, data) {
            $("#"+dmId).val(data.dm);
            $("#"+mcId).val(data.text);
            //关闭弹出div

            if($("#"+mcId).val().trim() != "") {//选择窗口触发onblur再次进行valid验证
                $("#"+mcId).blur();
            }
            closeTreeView();
        });

        //取消冒泡
        $("#treeDiv").on("click",function (e) {
            e.stopPropagation();
        })

        $("body").on("click",function () {
            closeTreeView();
        })
        var closeTreeView = function(){
            $("#treeDiv").slideUp(100);
            $('#tree').treeview('remove');
            $('#searchTree').val("");
        }
        var searchNodes = function (patt) {
            return $("#tree").treeview('search',[patt,{
                ignoreCase:false,
                exactMatch:false,
                revelResults:false
            }]);
        }
        $('#searchTree').on('keyup', function (e) {
            if(e.keyCode==13){
                checkableNodes = searchNodes($('#searchTree').val());
                if($("#tree .search-result").length>0){
                    $("#tree .list-group-item").hide();
                    $("#tree .list-group-item").each(function () {
                        if ($(this).hasClass("search-result")){
                            $(this).show();
                        }
                    })
                }else{
                    $("#tree .list-group-item").show();
                }
            }
        });

    })
}
//form表单转换为json格式，支持数组超过10
$.fn.serializeJsonObjectList = function() {
    var keyValues = this.serializeArray();
    var pattern=/\[(\d+)\]/;
    var filter_keys = [],
        normal_keys = keyValues.filter(function (v, i) {
            if (~v.name.indexOf('.')||~pattern.test(v.name)) {
                filter_keys.push(v);
                return false
            }
            return true;
        })

    var resultJson = {};
    filter_keys.forEach(function (v, i, ary) {
        var v_ary = v.name.split('.'),
            v_last = v_ary.length - 1;

        var deal = function (obj, j, array) {
            var me = arguments.callee,
                islast = j === v_last ? true : false;
            if (islast&&!pattern.test(array[j])) {
                if(typeof obj =='array'){
                    return obj.push(v.value);
                }else{
                    if(obj[array[j]]){
                        obj[array[j]]+=','+v.value||'';
                    }else{
                        obj[array[j]] = v.value || '';
                    }
                    return;
                }
            }else if(islast&&pattern.test(array[j])){
                var name = array[j].substr(0, array[j].indexOf('['));
                var index = array[j].match(pattern)[1];
                if (!obj[name]) {
                    obj[name] = [];
                }
                if (obj[name].length<= index) {
                    return obj[name].push(v.value||'');
                }
            }
            var nextObj;
            if (pattern.test(array[j])) {
                var name = array[j].substr(0, array[j].indexOf('['));
                var index = array[j].match(pattern)[1];
                if (!obj[name]) {
                    obj[name] = [];
                }
                if (obj[name].length<= index) {
                    nextObj={};
                    obj[name].push(nextObj);
                }else{
                    nextObj=obj[name][index];
                }
            } else {
                if (!obj[array[j]]) {
                    obj[array[j]] = {};
                }
                nextObj=obj[array[j]];
            }
            return me(nextObj, j + 1, array);
        }
        deal(resultJson, 0, v_ary);
    });
    normal_keys.forEach(function (v) {
        resultJson[v.name] = v.value;
    });
    return resultJson;
}
//form表单转换为json格式，支持数组不超过10
$.fn.serializeJsonObject = function() {
    var form = this.serializeArray();
    var json = {};
    $.each(form, function() {
        if (json[this.name]) {
            if (!json[this.name].push) {
                json[this.name] = [json[this.name]];
            }
            json[this.name].push(this.value || '');
        } else {
            json[this.name] = this.value || '';
        }
    });
    return json;
}
//页面中标签集合获取封装到json中
function getListParm(listName,param) {
    var list=[];
    $.each(param,function(n,value){
        if(n.indexOf(listName)==0){
            var proName = n.substr(n.lastIndexOf('.')+1);
            //var idx = n.substr(n.indexOf('[')+1,1);
            var idx = n.substring(n.indexOf('[')+1,n.indexOf(']'));
            if(!list[idx]){
                for (var i=list.length;i<=idx;i++){
                    list.push({});
                }
            }
            list[idx][proName] = value;
            delete param[n];
        }
    })
    param[listName] = list;
    return param;
}

//克隆元素时清除元素中value、重置元素ID、name、字典等
function initAddParm(oldNum,num,obj){
    //value值清空
    if (obj && ($(obj).attr("type")=='radio' || $(obj).attr("type")=='checkbox' ) ){
        //
    }else{
        $(obj).val("");
    }

    //修改ID
    var idName = $(obj).attr("id");
    if(idName){
        idName = idName.replace(oldNum,num);
        $(obj).attr("id",idName);
    }

    //修改name
    var nameName = $(obj).attr("name");
    if(nameName){
        nameName = nameName.replace(oldNum,num);
        $(obj).attr("name",nameName);
    }
    //修改字典代码指向ID
    var dicDmId = $(obj).attr("data-jzd-dm");
    if(dicDmId){
        dicDmId = dicDmId.replace(oldNum,num);
        $(obj).attr("data-jzd-dm",dicDmId);
    }
    //修改字典名称指向ID
    var dicMcId = $(obj).attr("data-jzd-mc");
    if(dicMcId){
        dicMcId = dicMcId.replace(oldNum,num);
        $(obj).attr("data-jzd-mc",dicMcId);
    }
    //修改字典清空的指向ID
    if($(obj).next().hasClass("form-control-feedback")){
        var oclval =$(obj).next().attr("onclick");
        var reg= new RegExp(oldNum,'g');
        oclval = oclval.replace(reg,num);
        $(obj).next().attr("onclick",oclval);
    }
    //修改时间类型input中最大、最小值限制的关联input
    var ofocs = $(obj).attr("onFocus");
    if(ofocs && ofocs.startsWith('WdatePicker')){
        var reg= new RegExp(oldNum,'g');
        ofocs = ofocs.replace(reg,num);
        $(obj).attr("onFocus",ofocs);
    }
}

/*
 js由毫秒数得到年月日
 使用： (new Date(data[i].creationTime)).Format("yyyy-MM-dd hh:mm:ss.S")
 */
Date.prototype.Format = function (fmt) { //author: meizz
    var o = {
        "M+": this.getMonth() + 1, //月份
        "d+": this.getDate(), //日
        "h+": this.getHours(), //小时
        "m+": this.getMinutes(), //分
        "s+": this.getSeconds(), //秒
        "q+": Math.floor((this.getMonth() + 3) / 3), //季度
        "S": this.getMilliseconds() //毫秒
    };
    if (/(y+)/.test(fmt)) fmt = fmt.replace(RegExp.$1, (this.getFullYear() + "").substr(4 - RegExp.$1.length));
    for (var k in o)
        if (new RegExp("(" + k + ")").test(fmt)) fmt = fmt.replace(RegExp.$1, (RegExp.$1.length == 1) ? (o[k]) : (("00" + o[k]).substr(("" + o[k]).length)));
    return fmt;
};
//获取初始化日期，格式为yyyy-MM-dd HH:mm:ss
Date.prototype.initDateTime = function (){
    return this.Format("yyyy-MM-dd hh:mm:ss");
    //设置开始日期为当前日期的前一个月
    date.setMonth(date.getMonth()-1);
    var begin = date.getFullYear() + "-" + (date.getMonth()+1) + "-" + date.getDate()+
        " " + date.getHours() + seperator2 + date.getMinutes() +seperator2 + date.getSeconds();

    $("#BeginTime").val(begin);
}

//获取初始化日期，格式为yyyy-MM-dd 00:00:00
Date.prototype.initDateZeroTime = function (){
    return this.initDateAndZeroTimeFmt('-',' ',':');
}
//获取初始化日期，格式为'yyyy'+seperator1+'MM'+seperator1+'dd'+seperator2+'00'+seperator3+'00'+seperator3+'00'
Date.prototype.initDateAndZeroTimeFmt = function (seperator1,seperator2,seperator3) {
    var month = this.getMonth() + 1;
    var strDate = this.getDate();
    if(month >= 1 && month <= 9) {
        month = "0" + month;
    }
    if(strDate >= 0 && strDate <= 9) {
        strDate = "0" + strDate;
    }
    var end = this.getFullYear() + seperator1 + month + seperator1 + strDate +seperator2 + '00' + seperator3 + '00' + seperator3 + '00';
    return end;
}
/**
 * 获取day天之后的日期，day为负数是为往前多少天
 * @param day
 */
Date.prototype.addDayNumByDate = function (day,fmt) {
    this.setDate(this.getDate()+day);
    return this.Format(fmt);
}
/**
 * 获取day月之后的日期，day为负数是为往前多少月
 * @param month
 */
Date.prototype.addMonthNumByDate = function (month,fmt) {
    this.setMonth(this.getMonth()+month);
    return this.Format(fmt);
}


var formEditValidate = function (formId) {
    $('#'+formId).validate({
        onFocus: function() {
            this.parent().addClass('active');
            return false;
        },
        onBlur: function() {
            this.val(this.val().trim());
            var $parent = this.parent();
            var _status = parseInt(this.attr('data-status'));
            $parent.removeClass('active');
            if (!_status) {
                $parent.addClass('error');
            }
            return false;
        }
    });
}

var formEditValidateReset = function (formId) {
    $('#'+formId).validate('resetValidate');
}


var N = [
    "零", "一", "二", "三", "四", "五", "六", "七", "八", "九"
];
var convertToChinese = function (num){
    var str = num.toString();
    var len = num.toString().length;
    var C_Num = [];
    for(var i = 0; i < len; i++){
        C_Num.push(N[str.charAt(i)]);
    }
    return C_Num.join('');
}

